package com.cqggrw.action;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.cqggrw.domain.Json;
import com.cqggrw.domain.User;
import com.cqggrw.service.UserServiceI;
import com.cqggrw.service.impl.UserServiceImpl;
import com.cqggrw.util.Utils;
import com.opensymphony.xwork2.ModelDriven;

public class UserAction extends BaseAction implements ModelDriven<User> {

	private static final long serialVersionUID = 1L;
	private UserServiceI service = new UserServiceImpl();
	public User user = new User();
	
	public String login() {
		String falg = "loginFaile";
		User u = service.login(user);
		if(user.getCode() == null || !user.getCode().equalsIgnoreCase((String)super.getAttributeBySession("code"))) {
			super.addAttributeForSession("message", "验证码错误！");
		}else if(u != null) {
			falg = "success";
			super.addAttributeForSession("user", u);
		} else {
			super.addAttributeForSession("message", "用户名或密码错误！");
		}
		return falg;
	}
	
	public void getImg() throws IOException {
		Map<String, Object> map = Utils.getImg();
		HttpServletResponse resp =ServletActionContext.getResponse();
		
		resp.setDateHeader("expries", -1);
		resp.setHeader("Cache-Control", "no-cache");
		resp.setHeader("Pragma", "no-cache");

		resp.setContentType("image/jpeg");
		Utils.log((String)map.get("code"));
		super.addAttributeForSession("code", map.get("code"));
		ImageIO.write((BufferedImage)map.get("imgIo"), "jpg", resp.getOutputStream());
		
	}
	
	public void query() {
		super.writeJson(service.get());
	}
	
	public void modify() {
		Json json = new Json();
		if (service.modify(user)) {
			json.setSuccess(true);
			json.setMsg("密码修改成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("密码修改失败!");
		}

		super.writeJson(json);
	}
	
	public void delete() {
		Json json = new Json();
		if (service.del(user.getId())) {
			json.setSuccess(true);
			json.setMsg("账号删除成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("账号删除失败!");
		}
		
		super.writeJson(json);
	}
	
	public void add() {
		Json json = new Json();
		if (service.add(user)) {
			json.setSuccess(true);
			json.setMsg("账号添加成功!");
		} else {
			json.setSuccess(false);
			json.setMsg("账号添加失败!");
		}
		
		super.writeJson(json);
	}

	public User getModel() {
		return user;
	}

	public void test() {
		Utils.closeApp = !(Utils.closeApp);
		super.writeJson(Utils.closeApp);
	}
}
